package com.minelx.datamicroscope.core.query;

import com.minelx.datamicroscope.core.display.Merger;
import com.minelx.hellopandas.core.DataFrame;
import io.gitee.minelx.filesystem.TempPath;

import java.util.List;

public class QueryPaths {

    private final ResourcesFactory resourcesFactory;

    private final FirstCollectionQuery firstCollectionQuery;

    private final List<QueryPath> queryPaths;

    public QueryPaths(ResourcesFactory resourcesFactory,
                      FirstCollectionQuery firstCollectionQuery,
                      List<QueryPath> queryPaths) {
        this.resourcesFactory = resourcesFactory;
        this.firstCollectionQuery = firstCollectionQuery;
        this.queryPaths = queryPaths;
    }

    public DataFrame query(String destinationURI, Merger merger) {
        try (TempPath firstCollectionTempPath = TempPath.random();
             Resources resources = resourcesFactory.makeResources(
                     firstCollectionQuery.rootResourceMapping(firstCollectionTempPath.file().path().uri()))) {
            QueryEmitter queryEmitter = resourcesFactory.createEmitter(resources);
            // append all query paths to container
            queryPaths.forEach(item -> item.append(queryEmitter));
            // merge to table
            return merger.merge(resources.resourceMappings(), destinationURI);
        }
    }
}
